package com.sinodata.bsm.cicp.collector.oracle;

import java.sql.ResultSet;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 磁盘排序比 单位 %
 * select a.value memory_value,b.value disk_value from v$sysstat a,v$sysstat b where a.name='sorts (memory)' and b.name='sorts (disk)'
 * 磁盘排序增量*100/(磁盘排序增量+内存排序增量)
 *
 * @author xuxiaoxiao
 *
 */
public class SortsDiskRateCollector extends AbstractJDBCCollector {

    //	public static void main(String[] args) {
    //		org.apache.log4j.PropertyConfigurator.configure("conf/log4j.properties");
    //
    //		SortsDiskRateCollector collector = new SortsDiskRateCollector();
    //		java.util.Map map = new java.util.HashMap();
    //		map.put("数据库类型", "oralce");
    //		map.put("数据库名", "orcl");
    //		map.put("SQL语句", "select a.value memory_value,b.value disk_value from v$sysstat a,v$sysstat b where a.name='sorts (memory)' and b.name='sorts (disk)'");
    //		collector.setParamMap(map);
    //		java.util.List list = collector.collect("192.168.0.102");
    //		com.union.pub.util.CollectorUtil.dumpCollectResult(list);
    //
    //	}

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        //        String dbtype = getParamMap().get("数据库类型");
        //        String dbname = getParamMap().get("数据库名");
        //        String sql = getParamMap().get("SQL语句");
        String dbtype = getParamMap().get("DBType");
        String dbname = getParamMap().get("DBName");
        String sql = getParamMap().get("SQL");
        logger.debug("sql=[" + sql + "]");
        String key = SortsDiskRateCollector.class.getName() + ":" + ip + ":" + dbname + ":" + ":" + dbtype;
        //java.sql.Connection conn = null;
        //java.sql.Statement st = null;
        ResultSet rs = null;
        Long tmpmemory = 0L;
        Long tmpdisk = 0L;
        try {
            //Class.forName("oracle.jdbc.driver.OracleDriver");
            //conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.102:1521:orcl", "jxum2", "orcl");
            //st = conn.createStatement();
            //rs = st.executeQuery(sql);
            rs = getCachedResultSet(dbtype, ip, dbname, sql);
            if (rs.next()) {
                tmpmemory = rs.getLong(1);
                tmpdisk = rs.getLong(2);
            }
            //System.out.println(tmpmemory+"#"+tmpdisk);
            String last_value = (String) getPersistentData(key);
            //将采集到得值进行临时保存，保存目录为 agent/save/..
            savePersistentData(key, tmpmemory + "#" + tmpdisk);
            if (last_value != null && tmpmemory >= 0 && tmpdisk >= 0) {
                //System.out.println(last_value);
                List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
                String[] propMetas = getPropMeta();
                ResPropertyValue propertyValueX = new ResPropertyValue();
                ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
                //计算出 磁盘排序比
                double rate = 0d;
                String tmpvalues[] = last_value.split("#");
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(2);

                long tmpmemoryvalue = tmpmemory - Long.parseLong(tmpvalues[0]);
                long tmpdiskvalue = tmpdisk - Long.parseLong(tmpvalues[1]);
                long sum = tmpmemoryvalue + tmpdiskvalue;
                if (sum != 0)
                    rate = 100.00 * tmpdiskvalue / sum;
                rate = rate > 0 ? rate : 0d;
                propValues[0] = ResPropertyValue.createPropValue(nf.format(rate), propMetas[0]);
                propertyValueX.setValues(propValues);
                values.add(propertyValueX);
                return values;
            }

        } catch (Exception e) {
            logger.error("Failed to get oracle sort disk information! ", e);
            throw new CollectorException("Failed to get oracle sort disk information! ", e);
        } finally {
            if (rs != null)
                try {
                    rs.close();
                } catch (Exception e) {
                }
        }

        return null;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "DBType", "DBName", "SQL" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "DiskSortRatio" };
    }

}
